<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    
    <div>发送消息</div>
    <input type="text" id="msgConten" value=""/>
    <button onclick="CHAT.chat()" >点我发送</button>

    <div>接受消息:</div>
    <div id="receiveMsg" style="background-color:gainsboro"></div>

    <script>

        window.CHAT = (function () {

        let obj =  { 
            socket : null , 
            init(){  
                if(window.WebSocket){

                    this.socket = new WebSocket("ws://localhost:8088/ws");

                    this.socket.onopen = ()=>{
                        console.log("连接建立成功")
                    }

                    this.socket.onclose = ()=>{
                        console.log("连接关闭")
                    }

                    this.socket.onerror = ()=>{
                        console.log("发生错误");
                    }

                    this.socket.onmessage = (e)=>{
                        console.log("接收到数据" + e.data);
                        let receiveMsg = document.getElementById("receiveMsg");

                        let element = document.createElement("p")

                        element.innerHTML = e.data ;

                        receiveMsg.appendChild(element);
                    }

                }else{
                    alert(" 当前的浏览器不支持 websocket")
                }
             },
             chat(){
                
               let text =  document.getElementById('msgConten');

               console.log(text.value);

               this.socket.send(text.value);

               alert("发送成功")

             } 
        }
        
        obj.init();

        return obj ;

        })()
        
     

       

    </script>

</body>
</html>